require 'net/http'
require 'uri'
require 'multi_json'
require 'top_notify/logger'
require 'top_notify/consumer'

module TopNotify
  class Server
    def initialize(consumer = Consumer.new)
      @consumer = consumer
    end

    def start
      loop do
        @conn = Connection.new
        connect
        sleep(1)
      end
    end

    private
    def connect
      Net::HTTP.start(@conn.uri.host, @conn.uri.port) do |http|
        http.request @conn.request do |response|
          if response.code.to_i == 400
            raise ConfigurationError.new('Your configuration is not correct, please check it.')
          end
          response.read_body do |chunk|
            begin
              json = MultiJson.load(chunk.strip)
            rescue
              logger.log_stream(chunk, "error occured when convert to json")
            end
            if json
              data = json['packet']
              result = TYPE[data['code'].to_i] || TYPE[0]
              logger.log_stream(data, result[:msg])
              @consumer.send(result[:method], data) if @consumer.respond_to?(result[:method])
            end
          end
        end
      end
    end

    def logger
      @logger ||= if TopNotify.logger
        Logger.new(TopNotify.logger)
      else
        Logger.new(STDOUT)
      end
    end
  end
end
